/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-04-02 13:58:15
 */

import { createContext, useContext, useReducer } from 'react';
import { ApproveReducer } from '../reducers/ApproveReducer';
import {
  HIDE_APPROVE_DIALOG,
  SET_APPROVE_LIST,
  SET_APPROVE_NAV,
  SET_QUERY,
  SHOW_APPROVE_DIALOG,
  SUBMIT_APPROVE
} from '../constants';
import {
  fetchBorrowProcessDetail,
  submitCurrentApprove,
  queryUnfinishedBorrowTasks,
  submitBorrowTask,
  queryApproveHisTasks
} from '@/api/workFlow/workflow';
import { EnumApproveNavTypes } from '@/view/use/Approve/dictionaries';

const initialState = {
  // 借阅管理列表
  borrowList: [],
  // 利用审批列表
  approveNav: EnumApproveNavTypes.Undo,
  approveList: [],
  approveLoading: false,
  approveQuery: {
    pageNo: 1,
    pageSize: 10,
    param: {}
  },

  // 选中的表格条目
  selectItems: [],

  approveDialog: {
    visible: false,
    data: null
  }
};

const ApproveContext = createContext();

const ApproveContextProvider = (props) => {
  const [state, dispatch] = useReducer(ApproveReducer, initialState);

  const actions = {
    setApproveNav(navKey) {
      dispatch({ type: SET_APPROVE_NAV, navKey });
    },

    /**
     * @description: 获取审核任务列表
     * @param {any} query
     */
    getApproveList(query) {
      return new Promise((resolve, reject) => {
        queryUnfinishedBorrowTasks(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_APPROVE_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 获取审核任务列表
     * @param {any} query
     */
    getApproveHisList(query) {
      return new Promise((resolve, reject) => {
        queryApproveHisTasks(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_APPROVE_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    setListQuery(info) {
      dispatch({ type: SET_QUERY, info });
    },

    /**
     * @description: 打开查看申请弹窗
     */
    showApproveDialog(info, dialogType) {
      fetchBorrowProcessDetail(info.applyForm.id).then((res) => {
        const { data } = res;
        data.taskId = info.taskId;
        data.processInstanceId = info.processInstanceId;
        dispatch({ type: SHOW_APPROVE_DIALOG, data, dialogType });
      });
    },

    /**
     * @description: 打开查看申请弹窗
     */
    hideApproveDialog() {
      dispatch({ type: HIDE_APPROVE_DIALOG });
    },

    /**
     * @description: 提交借阅申请审核 - 老
     * @param {*} params
     */
    submitApprove(params) {
      submitBorrowTask(params).then((res) => {
        const { data } = res;
        dispatch({ type: SUBMIT_APPROVE, taskId: data.taskId });
      });
    },

    /**
     * @description: 提交申请
     * @param {*} params
     */
    submitApproveFunc(params) {
      submitCurrentApprove(params).then(() => {
        dispatch({ type: HIDE_APPROVE_DIALOG, taskId: params.id });
      });
    },

    agreeApproveFun(params) {
      submitCurrentApprove(params).then((res) => {
        console.log('pass current approve', res.data);
      });
    }
  };

  const filters = {
    // stateFilter(id) {
    //   return state.AuditStateList.find((item) => item.id === id)?.name || '-';
    // }
  };

  // // watch query 加载列表
  // useEffect(() => {
  //   console.log('watch');
  //   if (state.approveQuery?.param?.assignee) {
  //     actions.getApproveList();
  //   }
  // }, [state.approveQuery]);

  return (
    <ApproveContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </ApproveContext.Provider>
  );
};

export const useApproveContext = () => {
  return useContext(ApproveContext);
};

export { ApproveContext, ApproveContextProvider };
